#include "lvgl/lvgl.h"
#include "lvgl/demos/lv_demos.h"
#include <unistd.h>
#include <pthread.h>
#include <time.h>
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <sys/wait.h>

#include  "gec_led.h"


// 自动浇水/施肥时间
volatile int auto_watering_hour = 8;
volatile int auto_watering_min = 0;
volatile int auto_manure_hour = 8;
volatile int auto_manure_min = 30;

void* watering_thread(void* arg);
void* spread_manure_thread(void* arg);

// 保存主界面对象，方便切换
lv_obj_t* main_screen = NULL;

// 全局变量
volatile int watering_running = 0;
volatile int manure_running = 0;
// 全局变量，记录音乐进程
pid_t music_pid = -1;

// 全局变量
lv_obj_t* main_panel = NULL;
lv_obj_t* setting_panel = NULL;

// 自动任务线程
void* auto_task_thread(void* arg)
{
    int watered_today = 0;
    int manured_today = 0;
    int last_day = -1;

    while (1)
    {
        time_t now = time(NULL);
        struct tm *tm_now = localtime(&now);

        // 调试输出当前时间和设定时间
        printf("当前时间: %02d:%02d, 浇水设定: %02d:%02d, 施肥设定: %02d:%02d, watered_today=%d, manured_today=%d, watering_running=%d, manure_running=%d\n",
            tm_now->tm_hour, tm_now->tm_min, auto_watering_hour, auto_watering_min, auto_manure_hour, auto_manure_min, watered_today, manured_today, watering_running, manure_running);

        // 每日重置标志
        if (tm_now->tm_mday != last_day)
        {
            watered_today = 0;
            manure_running = 0;
            last_day = tm_now->tm_mday;
        }

        // 到点自动浇水
        if (!watered_today && tm_now->tm_hour == auto_watering_hour && tm_now->tm_min == auto_watering_min)
        {
            if (!watering_running && !manure_running)
            {
                printf("自动浇水线程启动\n");
                pthread_t tid;
                pthread_create(&tid, NULL, watering_thread, NULL);
                pthread_detach(tid);
                watered_today = 1;
            } else {
                printf("浇水/施肥正在进行，自动浇水未触发\n");
            }
        }

        // 到点自动施肥
        if (!manured_today && tm_now->tm_hour == auto_manure_hour && tm_now->tm_min == auto_manure_min)
        {
            if (!watering_running && !manure_running)
            {
                printf("自动施肥线程启动\n");
                pthread_t tid;
                pthread_create(&tid, NULL, spread_manure_thread, NULL);
                pthread_detach(tid);
                manured_today = 1;
            } else {
                printf("浇水/施肥正在进行，自动施肥未触发\n");
            }
        }
        sleep(20); // 每20s检查一次
    }
    return NULL;
}

// 设置界面回调
static lv_obj_t* kb = NULL;
static lv_obj_t* ta_watering = NULL;
static lv_obj_t* ta_manure = NULL;

// 键盘事件回调
static void kb_event_cb(lv_event_t* e)
{
    lv_event_code_t code = lv_event_get_code(e);
    lv_obj_t* obj = lv_event_get_target(e);
    if (code == LV_EVENT_VALUE_CHANGED)
    {
        const char* txt = lv_btnmatrix_get_button_text(obj, lv_btnmatrix_get_selected_btn(obj));
        
        if (strcmp(txt, "OK") == 0)
        {
            // 解析输入并保存
            int wh, wm, mh, mm;
            sscanf(lv_textarea_get_text(ta_watering), "%d:%d", &wh, &wm);
            sscanf(lv_textarea_get_text(ta_manure), "%d:%d", &mh, &mm);
            if (wh >= 0 && wh < 24 && wm >= 0 && wm < 60)
            {
                auto_watering_hour = wh;
                auto_watering_min = wm;
            }
            if (mh >= 0 && mh < 24 && mm < 60)
            {
                auto_manure_hour = mh;
                auto_manure_min = mm;
            }
            // 隐藏设置界面，显示主界面
            lv_obj_add_flag(setting_panel, LV_OBJ_FLAG_HIDDEN);
            lv_obj_clear_flag(main_panel, LV_OBJ_FLAG_HIDDEN);
            // 关闭键盘
            if (kb) {
                lv_obj_del(kb);
                kb = NULL;
            }
        }
    }
}

// 文本框事件回调，弹出键盘
static void ta_event_cb(lv_event_t* e)
{
    lv_event_code_t code = lv_event_get_code(e);
    lv_obj_t* ta = lv_event_get_target(e);
    if (code == LV_EVENT_FOCUSED)
    {
        if (!kb)
        {
            kb = lv_keyboard_create(lv_screen_active());
            lv_keyboard_set_mode(kb, LV_KEYBOARD_MODE_TEXT_LOWER);
            lv_keyboard_set_textarea(kb, ta);
            lv_obj_add_event_cb(kb, kb_event_cb, LV_EVENT_ALL, NULL);
        }else
        {
            lv_keyboard_set_textarea(kb, ta);
        }
    }
}

// 收起键盘按钮的回调函数
void hide_keyboard_event_cb(lv_event_t* e)
{
    if (kb) {
        lv_obj_del(kb);
        kb = NULL;
    }
}

// 新增物理OK按钮的回调函数
void ok_btn_event_cb(lv_event_t* e)
{
    // 保存数据
    int wh, wm, mh, mm;
    sscanf(lv_textarea_get_text(ta_watering), "%d:%d", &wh, &wm);
    sscanf(lv_textarea_get_text(ta_manure), "%d:%d", &mh, &mm);
    if (wh >= 0 && wh < 24 && wm >= 0 && wm < 60)
    {
        auto_watering_hour = wh;
        auto_watering_min = wm;
    }
    if (mh >= 0 && mh < 24 && mm < 60)
    {
        auto_manure_hour = mh;
        auto_manure_min = mm;
    }
    // 隐藏设置界面，显示主界面
    lv_obj_add_flag(setting_panel, LV_OBJ_FLAG_HIDDEN);
    lv_obj_clear_flag(main_panel, LV_OBJ_FLAG_HIDDEN);
    // 关闭键盘
    if (kb) {
        lv_obj_del(kb);
        kb = NULL;
    }
}

// 设置界面
void show_setting_screen()
{
    lv_obj_t* scr = lv_scr_act();
    if (!setting_panel) {
        setting_panel = lv_obj_create(scr);
        lv_obj_set_size(setting_panel, 800, 480);

        // 加载支持中文的字体
        static lv_font_t *font_zh = NULL;
        static lv_style_t style_zh;
        if (!font_zh) {
            font_zh = lv_tiny_ttf_create_file("A:hei.TTF", 24); // 确保hei.TTF支持中文
            lv_style_init(&style_zh);
            lv_style_set_text_font(&style_zh, font_zh);
        }

        // 浇水时间label
        lv_obj_t* label1 = lv_label_create(setting_panel);
        lv_obj_add_style(label1, &style_zh, 0);
        lv_label_set_text(label1, "浇水时间(格式 HH:MM):");
        lv_obj_align(label1, LV_ALIGN_TOP_LEFT, 10, 20);

        ta_watering = lv_textarea_create(setting_panel);
        lv_obj_set_width(ta_watering, 100);
        lv_obj_set_height(ta_watering, 40);
        lv_obj_align_to(ta_watering, label1, LV_ALIGN_OUT_RIGHT_MID, 10, 0);
        char buf1[8];
        snprintf(buf1, sizeof(buf1), "%02d:%02d", auto_watering_hour, auto_watering_min);
        lv_textarea_set_text(ta_watering, buf1);
        lv_obj_add_event_cb(ta_watering, ta_event_cb, LV_EVENT_ALL, NULL);

        // 施肥时间label
        lv_obj_t* label2 = lv_label_create(setting_panel);
        lv_obj_add_style(label2, &style_zh, 0);
        lv_label_set_text(label2, "施肥时间(格式 HH:MM):");
        lv_obj_align(label2, LV_ALIGN_TOP_LEFT, 10, 120);
        ta_manure = lv_textarea_create(setting_panel);
        lv_obj_set_width(ta_manure, 100);
        lv_obj_set_height(ta_manure, 40);
        lv_obj_align_to(ta_manure, label2, LV_ALIGN_OUT_RIGHT_MID, 10, 0);
        char buf2[8];
        snprintf(buf2, sizeof(buf2), "%02d:%02d", auto_manure_hour, auto_manure_min);
        lv_textarea_set_text(ta_manure, buf2);
        lv_obj_add_event_cb(ta_manure, ta_event_cb, LV_EVENT_ALL, NULL);

        // 收起键盘按钮
        lv_obj_t* btn_hide_kb = lv_btn_create(setting_panel);
        lv_obj_set_size(btn_hide_kb, 80, 40);
        lv_obj_align(btn_hide_kb, LV_ALIGN_BOTTOM_RIGHT, -20, -250);
        lv_obj_t* label_hide_kb = lv_label_create(btn_hide_kb);
        lv_obj_add_style(label_hide_kb, &style_zh, 0);
        lv_label_set_text(label_hide_kb, "隐藏键盘");
        lv_obj_center(label_hide_kb);
        lv_obj_add_event_cb(btn_hide_kb, hide_keyboard_event_cb, LV_EVENT_CLICKED, NULL);

        // OK按钮
        lv_obj_t* btn_ok = lv_button_create(setting_panel);
        lv_obj_set_size(btn_ok, 80, 40);
        lv_obj_align_to(btn_ok, btn_hide_kb, LV_ALIGN_OUT_TOP_MID, 0, -10);
        lv_obj_t* label_ok = lv_label_create(btn_ok);
        lv_obj_add_style(label_ok, &style_zh, 0);
        lv_label_set_text(label_ok, "OK");
        lv_obj_center(label_ok);
        lv_obj_add_event_cb(btn_ok, ok_btn_event_cb, LV_EVENT_CLICKED, NULL);
    }
    lv_obj_add_flag(main_panel, LV_OBJ_FLAG_HIDDEN);
    lv_obj_clear_flag(setting_panel, LV_OBJ_FLAG_HIDDEN);
}

// 设置按钮回调
void event_handler_setting(lv_event_t* e)
{
    if (lv_event_get_code(e) == LV_EVENT_CLICKED)
    {
        show_setting_screen();
    }
}

// 浇水
void* watering_thread(void* arg)
{
    watering_running = 1;
    int fd = open("/dev/gec_led", O_RDWR);
    if (fd == -1)
    {
        perror("open led error");
        exit(1);
    }      
    ioctl(fd, LED_CTRL, "11");
    ioctl(fd, LED_CTRL, "21");
    sleep(15);
    ioctl(fd, LED_CTRL, "10");
    ioctl(fd, LED_CTRL, "20");
    close(fd);
    watering_running = 0;
    pthread_exit(NULL);
}

// 实现按钮按下开始浇水
void event_handler_watering(lv_event_t* e)
{
    // 获取事件代码（类型）
    lv_event_code_t code = lv_event_get_code(e);

    // 根据事件类型，执行不同的操作，LV_EVENT_CLICKD 表示点击按钮
    if (code == LV_EVENT_CLICKED)
    {
        // 判断是否在浇水
        if (watering_running)
        {
            // 正在进行不回应
            return;
        }
        pthread_t tid;
        pthread_create(&tid, NULL, watering_thread, NULL);
        pthread_detach(tid);  // 自动回收线程资源
    }
}

// 施肥
void* spread_manure_thread(void* arg)
{
    manure_running = 1;
    int fd = open("/dev/gec_led", O_RDWR);
    if (fd == -1)
    {
        perror("open led error");
        exit(1);
    }      
    ioctl(fd, LED_CTRL, "31");
    ioctl(fd, LED_CTRL, "41");
    sleep(15);
    ioctl(fd, LED_CTRL, "30");
    ioctl(fd, LED_CTRL, "40");
    close(fd);
    manure_running = 0;
    pthread_exit(NULL);
}
// 实现按钮按下开始施肥
void event_handler_spread_mabure(lv_event_t* e)
{
    // 获取事件代码（类型）
    lv_event_code_t code = lv_event_get_code(e);

    // 根据事件类型，执行不同的操作，LV_EVENT_CLICKD 表示点击按钮
    if (code == LV_EVENT_CLICKED)
    {
        // 判断是否在施肥
        if (manure_running)
        {
            // 正在进行不回应
            return;
        }
        pthread_t tid;
        pthread_create(&tid, NULL, spread_manure_thread, NULL);
        pthread_detach(tid);
    }
}

// 音乐
void* music_thread(void* arg)
{
    // 如果已有音乐在播放，直接返回
    if(music_pid > 0)
    {
        pthread_exit(NULL);
    }
    // 创建进程
    pid_t pid = fork();
    if (pid < 0)
    {
        perror("fork error");
        exit(1);
    }else if (pid == 0)
    {
        // 子进程
        int op = execlp("mplayer", "mplayer", "./1.mp3", NULL);
        if (op == -1)
        {
            perror("open mp3 error");
            _exit(1);
        }
    }else 
    {
        // 父进程，记录音乐进程pid
        music_pid = pid;
        pthread_exit(NULL);
    }
   
}
// 实现播放音乐
void event_handler_music(lv_event_t* e)
{
    // 获取事件代码（类型）
    lv_event_code_t code = lv_event_get_code(e);

    // 根据事件类型，执行不同的操作
    if (code == LV_EVENT_CLICKED)
    {
        if (music_pid > 0)
        {
            // 有音乐在播放，发生SIGTERM关闭
            kill(music_pid, SIGTERM);
            music_pid = -1;
        }else
        {
            // 没有音乐在播放，启动音乐线程
            pthread_t tid;
            pthread_create(&tid, NULL, music_thread, NULL);
            pthread_detach(tid);
        }
    }
        
}

// 逐字显示文本的定时器回调函数（循环滚动）
static const char* full_text = "智能植物培养系统 - 自动浇水施肥 - 音乐播放 - 时间设置";
static int char_index = 0;

static void text_timer_cb(lv_timer_t* timer) 
{
    lv_obj_t* label = (lv_obj_t*)timer->user_data;
    if (char_index < strlen(full_text)) {
        char temp_text[256];
        strncpy(temp_text, full_text, char_index + 1);
        temp_text[char_index + 1] = '\0';
        lv_label_set_text(label, temp_text);
        char_index++;
    } else {
        // 显示完后，重置，循环滚动
        char_index = 0;
        lv_label_set_text(label, ""); // 清空，准备下一轮
    }
}

void setup_ui()
{
    lv_obj_t* scr = lv_scr_act();
    if (!main_panel) {
        main_panel = lv_obj_create(scr);
        lv_obj_set_size(main_panel, 800, 480);

        // 设置三个按钮
        lv_obj_t* btn_watering = lv_button_create(main_panel);
        lv_obj_t* btn_spread_manure = lv_button_create(main_panel);
        lv_obj_t* btn_music = lv_button_create(main_panel);
        lv_obj_t* btn_setting = lv_button_create(main_panel);

        // 给按钮加上标签，用来显示文本
        lv_obj_t* label_watering = lv_label_create(btn_watering);
        lv_obj_t* label_spread_manure = lv_label_create(btn_spread_manure);
        lv_obj_t* label_music = lv_label_create(btn_music);
        lv_obj_t* label_setting = lv_label_create(btn_setting);

        // 设置标签的文本
        static lv_style_t style;
        lv_style_init(&style);
        // 创建字体对象, 字体文件没有带路径表示当前目录
        lv_font_t *font = lv_tiny_ttf_create_file("A:hei.TTF", 24);
        // 设置样式中的文本字体
        lv_style_set_text_font(&style, font);
        lv_style_set_text_align(&style, LV_TEXT_ALIGN_CENTER);
        lv_obj_add_style(label_watering, &style, 0);
        lv_label_set_text(label_watering, "浇水");
        lv_obj_center(label_watering);

        lv_obj_add_style(label_spread_manure, &style, 0);
        lv_label_set_text(label_spread_manure, "施肥");
        lv_obj_center(label_spread_manure);

        lv_obj_add_style(label_music, &style, 0);
        lv_label_set_text(label_music, "音乐");
        lv_obj_center(label_music);

        lv_obj_add_style(label_setting, &style, 0);
        lv_label_set_text(label_setting, "设置时间");
        lv_obj_center(label_setting);

        // 设置按钮位置
        lv_obj_align(btn_watering, LV_ALIGN_BOTTOM_MID,-150, 0);
        lv_obj_align(btn_spread_manure, LV_ALIGN_BOTTOM_MID, 0, 0);
        lv_obj_align(btn_music, LV_ALIGN_BOTTOM_MID, 150, 0);
        lv_obj_align(btn_setting, LV_ALIGN_BOTTOM_MID, 0, -100);

        // 给按钮绑定回调函数
        lv_obj_add_event_cb(btn_watering, event_handler_watering, LV_EVENT_ALL, NULL);
        lv_obj_add_event_cb(btn_spread_manure, event_handler_spread_mabure, LV_EVENT_ALL, NULL);
        lv_obj_add_event_cb(btn_music, event_handler_music, LV_EVENT_ALL, NULL);  
        lv_obj_add_event_cb(btn_setting, event_handler_setting, LV_EVENT_CLICKED, NULL);

        // 添加滚动文本区域 - 智能植物培养
        lv_obj_t* scroll_label = lv_label_create(main_panel);
        lv_obj_add_style(scroll_label, &style, 0); // 使用相同的字体样式
        lv_label_set_text(scroll_label, "智能植物培养系统 - 自动浇水施肥 - 音乐播放 - 时间设置");
        lv_obj_set_width(scroll_label, 780); // 设置宽度
        lv_obj_align(scroll_label, LV_ALIGN_TOP_MID, 0, 20);
        
        // 设置文本滚动动画
        lv_anim_t a;
        lv_anim_init(&a);
        lv_anim_set_var(&a, scroll_label);
        lv_anim_set_values(&a, 400, -400); // 从右向左滚动
        lv_anim_set_time(&a, 8000); // 8秒滚动一次
        lv_anim_set_delay(&a, 1000); // 1秒后开始
        lv_anim_set_exec_cb(&a, (lv_anim_exec_xcb_t)lv_obj_set_x);
        lv_anim_set_path_cb(&a, lv_anim_path_linear);
        lv_anim_set_repeat_count(&a, LV_ANIM_REPEAT_INFINITE); // 无限重复
        lv_anim_start(&a);
    }
    lv_obj_clear_flag(main_panel, LV_OBJ_FLAG_HIDDEN);
}


int main(void)
{
    lv_init();

    /*Linux frame buffer device init*/
    lv_display_t * disp = lv_linux_fbdev_create();
    lv_linux_fbdev_set_file(disp, "/dev/fb0");

    //初始化触摸屏幕
    lv_evdev_create(LV_INDEV_TYPE_POINTER,"/dev/input/event0");

    //获取lvgl默认的空间界面
    lv_obj_t* src = lv_screen_active();

    // 重置灯光
    int fd = open("/dev/gec_led", O_RDWR);
    if (fd == -1)
    {
        perror("open led error");
        exit(1);
    } 
    ioctl(fd,LED_ALL_ON);
	usleep(300000);
	ioctl(fd,LED_ALL_OFF);
	usleep(300000);
    
    setup_ui();

    // 启动自动任务线程
    pthread_t auto_tid;
    pthread_create(&auto_tid, NULL, auto_task_thread, NULL);
    pthread_detach(auto_tid);

    /*Handle LVGL tasks*/
    while(1) {
        lv_timer_handler();
        usleep(5000);

        // 检查音乐进程是否已退出
        if (music_pid > 0)
        {
            int status;
            pid_t result = waitpid(music_pid, &status, WNOHANG);
            if (result == music_pid)
            {
                music_pid = -1;
            }
        }
    }

    return 0;
}
